<?php
/**
 * Created by PhpStorm.
 * User: YanZ
 * Date: 15/11/12
 * Time: 下午1:35
 */

namespace Home\Controller;


use Home\Common\BizCode;
use Home\Common\Response;
use Home\Common\Gateway;
use Think\Cache;
use Think\Cache\Driver\Redis;
use Think\Controller\RestController;
use Think\Exception;

class OrderController extends RestController
{

    private $user;

    public function _initialize()
    {
        $this->user = session('user');

        if (!$this->user) {
            $response = new Response();
            $response->setFailState('UN_LOGIN');
            $this->response($response, 'json');
            exit;
        }
    }

    //获取订单详细信息
    public function getOrder()
    {
        $uid = $this->getUserId();
        $response = new Response();
        $oid = I("order_id");
        $Dao = D('Order');
        $response->addData("order", $Dao->relation('order_products')->where('user_id = %d and order_id = %d', $uid, $oid)->find());
        $this->response($response, 'json');
    }

    //获取登陆用户Orders
    public function getUserOrder()
    {
        $response = new Response();
        $uid = $this->getUserId();

        // $orders = searchCacheBeforeDB("user:" . $uid . ":orders", function () use ($uid) {
        //     $Dao = D('Order');
        //     return  $Dao->relation('order_products')->where('user_id = %d', $uid)->order('createtime desc')->select();
        // });
        $Dao = D('Order');
        $orders = $Dao->relation('order_products')->where('user_id = %d', $uid)->order('createtime desc')->select();
        $response->addData("orders", $orders);
        $this->response($response, 'json');
    }

    //修改订单状态
    // 0--已发货|1--已付款|2--已完成(评价)|3--待退货|4--已退货
    public function changeOrderStatus()
    {
        $response = new Response();
        $status = I("status");
        $oid = I("id");
        $uid = $this->getUserId();
        $data = array("status" => $status);
        if($status == '3'){
          $data['returntime'] = date('Y-m-d H:i:s', time());
        }
        $order = M("order")->where("order_id = %d and user_id = %d", $oid, $uid)->setField($data);
        $response->addData("orders", $order);
        $this->response($response, 'json');
    }

    // 添加评论  list>product_id, score, comment
    public function addComment(){
        $response = new Response();
        $comments = I("param.comments");
        $order_id = I('id');
        $uid = $this->getUserId();

        $Dao = M("product_comment");
        $Dao->startTrans();
        foreach($comments as &$comment){
            $r = $Dao->add(array(
                "user_id" => $uid,
                "product_id" => $comment['product_id'],
                "score" => $comment['score'],
                "comment" => $comment['comment'],
            ));
            if(!$r){
                $Dao->rollback();
                $response->setFailState('ORDER_COMMENT_ERROR');
                $this->response($response, 'json');
                exit;
            }
        }

        // 设置已经评论
        $r = M('order')->where('order_id = %d', $order_id)->setField('status', 2);
        if(!$r){
            $Dao->rollback();
            $response->setFailState('ORDER_COMMENT_ERROR');
            $response->addData("id", $order_id);

            $this->response($response, 'json');
            exit;
        }

        $Dao->commit();
        $response->addData("comment", $comments);
        $this->response($response, 'json');
    }

    private function clearCacheData($uid, $products){
      foreach ($products as $key => $value) {
        $value = (object) $value;
        initLimitationFromDB($uid, $value->product_discount_id);
      }
    }

    private function isWorkTime()
    {
      $time = date('H');
      $time = intval($time);

//        return true;
      return $time >= 9 && $time < 21;
    }


    // products, loc, district, note
    public function createOrder()
    {
        $response = new Response();
        if(!$this->isWorkTime()){
          $response->setFailState('ORDER_TIMEOUT');
          $this->response($response, 'json');
          exit;
        }

       $data = json_decode(file_get_contents("php://input", true));
      //  var_dump($data);
       if($data != null){
          $products = $data->products;
          $loc = $data->loc;
          $district = $data->district;
          $note = $data->note;
       } else {
         $products = I('param.products');
         $loc = (object)I('param.loc');
         $district = (object)I('param.district');
         $note = I('param.note');
       }

        $temp = D('Arepository')->relation(true)->find($district->a_repository_id);

        if($temp['status'] != '0'){
            $response->state = array("code" => '521', 'message' => '该仓库已停止下单');

            $response->addData('temp', $temp);
            $this->response($response, 'json');
            exit;
        }

        // var_dump($products);
        if (!is_array($products) || count($products) < 1 || is_null($loc) || empty($loc)) {
            $response->setFailState('PARAM_INVALID');
            // $response->addData('products',I(''));
            $this->response($response, 'json');
            exit;
        }

        $dao = M("order");
        $dao->startTrans();
//
//            创建订单
        $uid = $this->getUserId();

        $prefix = date("Ymd");  //生成唯一标识
        $oid = $dao->add(array(
            'user_id' => $uid,
            'order_serial_id' => uniqid($prefix),
            'deliver_serial_id' => uniqid($prefix),
            'receivename' => $loc->receivename,
            'address' => $loc->detail,
            'phone' => $loc->phone,
            'status' => '0',
            'note' => $note
        ));

        //创建订单商品
        $amount = 0; // 订单总金额
        $realamount = 0; // 订单应付金额
        $totalnum = 0;
        $isSendFreeWhen9 = false; // 是否满9包邮
        try {

          foreach ($products as &$p) {
  //                echo $p->product_id.'. barcode: '.$p->barcode;
              $p = (object)$p;
              if($p->tag == '1'){
                $isSendFreeWhen9 = true;
              }

              if($p->status == '1'){
                  $dao->rollback();
                  $response->state = array("code" => '521', 'message' => '商品已下架,请清空购物车再下单');

                  $this->response($response, 'json');
                  $this->clearCacheData($uid, $products);
                  exit;
              }
              if ((is_null($p->product_discount_id) || empty($p->product_discount_id) || $p->product_discount_id == '0')) {
                  $realprice = $p->kj_price;
              } else {
                  $realprice = $p->cx_price;
              }
              $realamount += (float)$realprice * (float)$p->num;
              $amount += (float)$p->kj_price * (float)$p->num;
              $totalnum += (int)$p->num;
              $order_product = array(
                  'order_id' => $oid,
                  'product_id' => $p->product_id,
                  'product_discount_id' => $p->product_discount_id,
                  'barcode' => $p->barcode,
                  'name' => $p->name,
                  'subname' => $p->subname,
                  'class1' => $p->class1,
                  'class2' => $p->class2,
                  'class3' => $p->class3,
                  'smimgurl' => $p->smimgurl,
                  'tag' => $p->tag,
                  'scale' => $p->scale,
                  'a_repository_id' => $p->a_repository_id,
                  'b_repository_id' => $p->b_repository_id,
                  'sendtype' => $p->sendtype,
                  'kj_price' => $p->kj_price,
                  'num' => $p->num,
                  'realprice' => $realprice,
                  'status' => '0',
              );

              if(!isset($a_id) && !empty($p->a_repository_id)){
                $a_id = $p->a_repository_id;
              }

              if(!isset($b_id) && !empty($p->b_repository_id)){
                  $a_id = $district->a_repository_id;
                  $b_id = $p->b_repository_id;
              }


              $productname = $p->name;

              // 减少商品数量
              if (!is_null($p->product_discount_id) && !empty($p->product_discount_id) && $p->product_discount_id != '0') {
                  // $response->addData('test', 0);

                  // 检查限购
                  $r = checkAndBuy($uid, $p->product_discount_id, $p->num);
                  if($r >= 0) {

                    // $response->addData('test', $p->num - 0);

                    $dao = M('product_discount');

                    $r1 = M('product')->where('product_id = %d', $p->product_id)->setDec('default_amount', $p->num - 0);

                    if($r1 > 0){
                      $leftnum = $dao->where('product_discount_id = %d', $p->product_discount_id)->field('remain_amount')->find();
                      $leftnum = $leftnum['remain_amount'];
                      $r1 = $dao->where('product_discount_id = %d', $p->product_discount_id)->setDec('remain_amount', $p->num - 0);
                    } else {
                      $leftnum = $dao->where('product_discount_id = %d', $p->product_discount_id)->field('remain_amount')->find();
                      $leftnum = $leftnum['remain_amount'];
                      $r1 = $dao->where('product_discount_id = %d', $p->product_discount_id)->setField(array('remain_amount' => 0));
                    }
                  } else {

                    $this->clearCacheData($uid, $products);
                    $dao->rollback();
                    $response->setFailState('ORDER_GOODS_DISCOUNT_LIMIT');
                    $this->response($response, 'json');
                    exit;
                  }
              } else {
                  $leftnum = M('product')->where('product_id = %d', $p->product_id)->field('default_amount')->find();
                  $leftnum = $leftnum['default_amount'];
  // //                var_dump($p);
                  $r = M('product')->where('product_id = %d', $p->product_id)->setDec('default_amount', $p->num - 0);
  //                 if (!$r) {
  // //                    echo '1';
  //                     $this->clearCacheData($uid, $products);
  //
  //                     $dao->rollback();
  //                     $response->setFailState('ORDER_GOODS_NUM_NOT_ENOUGH');
  //                     $this->response($response, 'json');
  //                     exit;
  //                 }
              }

              $OrderProductDao = M("order_product");
              $order_product->order_product_id = $OrderProductDao->add($order_product);

              // 从购物车删除
              $r = M('shopping_cart')->delete($p->shopping_cart_id);
              if (!$r) {
                $dao->rollback();
                $this->clearCacheData($uid, $products);

                $response->setFailState('ORDER_CART_NOT_EXIST');
                $this->response($response, 'json');
                exit;
              }
          }
        } catch (Exception $e) {
          $dao->rollback();
          // var_dump($dao);
          // $response->addData('e', $e);
          // $response->setFailState('ORDER_GOODS_NUM_NOT_ENOUGH');
          $response->state = array("code" => '520', 'message' => '商品"'.$productname.'"库存仅为'.$leftnum);

          $this->response($response, 'json');
          $this->clearCacheData($uid, $products);

          exit;
        }

        // 小于9元，加运费
        $sendprice = $realamount >= 9 && $isSendFreeWhen9? 0 : 6;
        $r = M('order')->where('order_id = %d', $oid)->setField(array('realprice' => $realamount, 'price' => $amount, 'num' => $totalnum, 'sendprice' => $sendprice, 'a_repository_id'=>$a_id, 'b_repository_id'=>$b_id));

        $dao->commit();
        $response->addData('orderid', $oid);
        $response->addData('order', I('param.'));

        $this->notifyCreate($a_id, $b_id);
        $this->response($response, 'json');
    }

    private function notifyCreate($aid, $bid){
        if($aid != null && $aid != 0 && $aid != ''){
            $group = $aid.'_';
            $message = array('type' => 'new_order', 'message' => '您有一笔新的订单');
            Gateway::sendToGroup($group, json_encode($message));
        }
        if($bid != null && $bid != 0 && $bid != ''){
            $group = '_'.$bid;
            $message = array('type' => 'new_order', 'message' => '您有一笔新的订单');
            Gateway::sendToGroup($group, json_encode($message));
        }
    }

    //获取当前用户id
    private function getUserId()
    {
        return isset($this->user) ? $this->user['user_id'] : 0;
    }

    private function getOrderDetail($id)
    {
        return M('order')->find($id);
    }
}
